package com.bckj.fastboot.core.extra.extpt;

import com.bckj.fastboot.core.extra.stage.StageRepository;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "fastboot.extpt", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(FastExtPtProperties.class)
public class FastExtPtConfiguration {

    @Bean
    public DynamicExtPtGenerator dynamicExtPtGenerator(StageRepository stageRepository) {
        return new DynamicExtPtGenerator(stageRepository);
    }

    @Bean
    public DynamicExtPtRepository dynamicExtPtRepository() {
        return new DynamicExtPtRepository();
    }

    @PostConstruct
    public void init(FastExtPtProperties properties, DynamicExtPtGenerator dynamicExtPtGenerator, DynamicExtPtRepository dynamicExtPtRepository) {
        for (ExtPtProfile profile : properties.getProfiles()) {
            try {
                Object generate = dynamicExtPtGenerator.generate(profile);
                dynamicExtPtRepository.put(profile.getBeanName(), generate);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
